package com.ruoyi.flow.flow.identity;

import com.ruoyi.flow.auth.security.FlowUser;
import com.ruoyi.flow.auth.security.FlowUserDetailService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.GroupQuery;
import org.activiti.engine.identity.User;
import org.activiti.engine.identity.UserQuery;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by fenghuo on 2018/8/23.
 */
@Service("idService")
public class FlowIdentityService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FlowIdentityService.class);
    @Autowired
    private IdentityService identityService;
    @Autowired
    private FlowUserDetailService userDetailService;

    /**
     * 获取用户信息
     *
     * @param groupId
     * @param userId
     * @return
     */
    public List<User> getUsers(String groupId, String userId) {
        UserQuery userQuery = identityService.createUserQuery();
        if (StringUtils.isNotEmpty(groupId)) {
            userQuery.memberOfGroup(groupId);
        }
        if (StringUtils.isNotEmpty(userId)) {
            userQuery.userId(userId);
        }
        List<User> users = userQuery.orderByUserFirstName().asc().list();
        return users;
    }

    /**
     * 获取用户组
     *
     * @return
     */
    public List<Group> getGroups() {
        GroupQuery groupQuery = identityService.createGroupQuery();
        return groupQuery.list();
    }

    /**
     * 根据用户组ID获取用户组
     *
     * @param groupId
     * @return
     */
    public GroupEntity getGroupByGroupId(String groupId) {
        return (GroupEntity) identityService.createGroupQuery().groupId(groupId).singleResult();
    }

    /**
     * 根据用户ID获取用户对象
     *
     * @param userId
     * @return
     */
    public FlowUser getUserByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            LOGGER.error("the parameter userid is null or empty");
            return null;
        }
        return (FlowUser) userDetailService.loadByUserId(userId);
    }
}
